import Cookies from "js-cookie"

export const setCookie = (key, value, cookieExpires) => {
    Cookies.set(`system_${key}`, value, {
        expires: cookieExpires || 1
    })
}

export const getCookie = (key) => {
    const cookie = Cookies.get(`system_${key}`);
    if (cookie && cookie !== "undefined") return cookie;
    else return false;
}

export const Debounce = (fn, t) => {
    let delay = t || 500;
    let timer;
    return function () {
        let args = arguments;
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            timer = null;
            fn.apply(this, args);
        }, delay);
    };
};

export const Throttle = (fn, t) => {
    let last;
    let timer;
    let interval = t || 500;
    return function () {
        let args = arguments;
        let now = +new Date();
        if (last && now - last < interval) {
            clearTimeout(timer);
            timer = setTimeout(() => {
                last = now;
                fn.apply(this, args);
            }, interval);
        } else {
            last = now;
            fn.apply(this, args);
        }
    };
};